import Menu from 'ant-design-vue/es/menu';
import Icon from 'ant-design-vue/es/icon';
import { deleteAction, postAction } from '@/api/manage';

const { Item, SubMenu } = Menu;

export default {
  name: 'SMenu',
  props: {
    menu: {
      type: Array,
      required: true,
    },
    theme: {
      type: String,
      required: false,
      default: 'dark',
    },
    mode: {
      type: String,
      required: false,
      default: 'inline',
    },
    collapsed: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  data() {
    return {
      openKeys: [],
      selectedKeys: [],
      cachedOpenKeys: [],
      renderKey: 0, // 用于强制重新渲染
    };
  },
  computed: {
    rootSubmenuKeys: (vm) => {
      const keys = [];
      vm.menu.forEach((item) => keys.push(item.path));
      return keys;
    },
  },
  mounted() {
    this.updateMenu();
  },
  watch: {
    collapsed(val) {
      if (val) {
        this.cachedOpenKeys = this.openKeys.concat();
        this.openKeys = [];
      } else {
        this.openKeys = this.cachedOpenKeys;
      }
    },
    $route() {
      this.updateMenu();
    },
  },
  methods: {
    onOpenChange(openKeys) {
      if (this.mode === 'horizontal') {
        this.openKeys = openKeys;
        return;
      }
      const latestOpenKey = openKeys.find((key) => !this.openKeys.includes(key));
      if (!this.rootSubmenuKeys.includes(latestOpenKey)) {
        this.openKeys = openKeys;
      } else {
        this.openKeys = latestOpenKey ? [latestOpenKey] : [];
      }
    },
    updateMenu() {
      const routes = this.$route.matched.concat();
      const { hidden } = this.$route.meta;
      if (routes.length >= 3 && hidden) {
        routes.pop();
        this.selectedKeys = [routes[routes.length - 1].path];
      } else {
        this.selectedKeys = [routes.pop().path];
      }
      let openKeys = [];
      if (this.mode === 'inline') {
        routes.forEach((item) => {
          openKeys.push(item.path);
        });
      }
      if (this.selectedKeys[0].includes(':')) {
        const selectedKey = this.$route.fullPath;
        this.selectedKeys = [selectedKey];
        const newOpenKeys = [];
        this.fullOpenKeys(this.menu, selectedKey, newOpenKeys);
        if (newOpenKeys.length > 0) {
          openKeys = newOpenKeys.reverse();
        }
      }
      if (!this.selectedKeys || this.selectedKeys[0].indexOf(':') < 0) {
        this.collapsed ? (this.cachedOpenKeys = openKeys) : (this.openKeys = openKeys);
      }
    },
    fullOpenKeys(menus, selectedKey, openKeys) {
      for (const item of menus) {
        if (item.path === selectedKey) {
          openKeys.push(item.path);
          this.$emit('updateMenuTitle', item);
          return true;
        } else if (Array.isArray(item.children)) {
          if (this.fullOpenKeys(item.children, selectedKey, openKeys)) {
            openKeys.push(item.path);
            return true;
          }
        }
      }
    },
    renderItem(menu) {
      if (!menu.hidden) {
        return menu.children && !menu.alwaysShow ? this.renderSubMenu(menu) : this.renderMenuItem(menu);
      }
      return null;
    },
    renderMenuItem(menu) {
      const target = menu.meta.target || null;
      const tag = target && 'a' || 'router-link';
      const props = menu.route && menu.route === '0' ? { to: { path: menu.path } } : { to: { name: menu.name } };
      const attrs = { href: menu.path, target: menu.meta.target };

      if (menu.children && menu.alwaysShow) {
        menu.children.forEach((item) => {
          item.meta = Object.assign(item.meta, { hidden: true });
        });
      }

      // 判断当前菜单是否选中
      const isSelected = this.selectedKeys.includes(menu.path);

      // 收藏图标样式
      const starIconStyle = {
        position: 'absolute',
        right: '-6px',
        top: '10px',
        fontSize: '20px',
        color: menu.meta.isFav ? 'orange' : 'inherit', // 收藏时为橙色，否则为默认颜色
        cursor: 'pointer', // 鼠标悬停时显示为手型
        opacity: isSelected ? 1 : 0, // 选中菜单始终显示，非选中菜单默认隐藏
        transition: 'opacity 0.3s', // 添加过渡效果
      };

      // 收藏图标点击事件
      const handleFavClick = (event) => {
        event.stopPropagation(); // 阻止事件冒泡
        event.preventDefault(); // 阻止默认行为（如果有）
        const newFavStatus = !menu.meta.isFav;
        const action = newFavStatus ? postAction : deleteAction;
        const url = newFavStatus ? '/sys/myCollection/add' : '/sys/myCollection/delete';
        const params = newFavStatus ? [{ permissionId: menu.id }] : { id: menu.id };

        action(url, params).then((res) => {
          if (res.success) {
            this.$set(menu.meta, 'isFav', newFavStatus); // 更新收藏状态
            this.updateStatus(); // 手动调用 render() 函数
          }
        });
      };

      // 鼠标移入时显示图标（仅对非选中菜单生效）
      const handleMouseEnter = (event) => {
        if (!isSelected) {
          event.domEvent.target.querySelector('.star-icon').style.opacity = 1;
        }
      };

      // 鼠标移出时隐藏图标（仅对非选中菜单生效）
      const handleMouseLeave = (event) => {
        if (!isSelected) {
          event.domEvent.target.querySelector('.star-icon').style.opacity = 0;
        }
      };

      return (
        <Item {...{ key: menu.path }} style="position:relative;" onMouseenter={handleMouseEnter} onMouseleave={handleMouseLeave}>
          <tag {...{ props, attrs }}>
            {this.renderIcon(menu.meta.icon)}
            <span>{menu.meta.title}</span>
          </tag>
          <a-icon class="star-icon" type="star" style={starIconStyle} theme={menu.meta.isFav ? 'filled' : 'outlined'} onClick={handleFavClick} />
        </Item>
      );
    },
    renderSubMenu(menu) {
      const itemArr = [];
      if (!menu.alwaysShow) {
        menu.children.forEach((item) => itemArr.push(this.renderItem(item)));
      }
      return (
        <SubMenu {...{ key: menu.path }}>
          <span slot="title">
            {this.renderIcon(menu.meta.icon)}
            <span>{menu.meta.title}</span>
          </span>
          {itemArr}
        </SubMenu>
      );
    },
    renderIcon(icon) {
      if (icon === 'none' || icon === undefined) {
        return null;
      }
      const props = typeof icon === 'object' ? { component: icon } : { type: icon };
      return <Icon {...{ props }} />;
    },
    updateStatus() {
      this.renderKey += 1; // 修改 key 的值，强制重新渲染
    },
  },
  render() {
    const { mode, theme, menu } = this;
    const props = {
      mode: mode,
      theme: theme,
      openKeys: this.openKeys,
    };
    const on = {
      select: (obj) => {
        this.selectedKeys = obj.selectedKeys;
        this.$emit('select', obj);
      },
      openChange: this.onOpenChange,
    };

    const menuTree = menu.map((item) => {
      if (item.hidden) {
        return null;
      }
      return this.renderItem(item);
    });

    return (
      <Menu key={this.renderKey} vModel={this.selectedKeys} {...{ props, on: on }}>
        {menuTree}
      </Menu>
    );
  },
};